#include <QGridLayout>
#include <QVBoxLayout>
// #include <QTextCodec>
#include <QCloseEvent>
#include <QAction>
#include <QMenu>
#include <QTimer>
#include <QApplication>
#include <QSettings>
#include <QProcess>
#include <QVariant>
#include <QSplitter>
#include <QTextCodec>
#include <QWidget>
#include <QDebug>

#ifdef WIN32
#include <QMessagebox>
#else
#include <QMessageBox>
#endif

#include "mainwindow.h"
#include "version.h"
#include "CloseCheck.h"

#include "WinViewStyle/mymenubar.h"
#include "WinViewStyle/mymenu.h"
#include "WinViewStyle/mytoolbar.h"
#include "WinViewStyle/mystatusbar.h"

#include "SA_view/SAView.h"
#include "src/confdeal.h"

#ifdef WIN32

#ifdef VSWIN_32
#undef VSWIN_32
#endif

#ifndef QTWIN_32
#define QTWIN_32
#endif

#endif

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
{
	init();
    #ifdef _MIN_WIN_
	initTray();
    #endif
}

MainWindow::~MainWindow()
{
}

void MainWindow::init()
{
    view = new SAView;
    connect(view, SIGNAL(showMsg(QString)), this, SLOT(showMsg(QString)));
    this->setCentralWidget(view);

	createActions();
    createMenus();
    createToolBars();
    createStatusBar();

	// QString _appname = "";
	// _appname = STR_VERSION_PRODUCTNAME;
	// _appname += STR_VERSION_VERSION;
	QIcon _icon = QIcon(":/resource/applog.png");

    this->setWindowTitle(tr("history_curve_for_pyfree-IotEdge"));
	// this->setWindowIcon(_icon);

	this->setMinimumSize(800, 600);
    // this->setMaximumSize(1600, 1200);
	// this->setWindowState(Qt::WindowMaximized);
	this->setAutoFillBackground(true);
	this->setContentsMargins(0,0,0,0);
	this->setFontFormat(); 
}

void MainWindow::createActions()
{
    exitAct = new QAction(QIcon(":resource/exit.png"),tr("Exit"), this);
    exitAct->setShortcut(tr("Ctrl+Q"));
    exitAct->setStatusTip(tr("Exit the application"));
    // connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
    connect(exitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
    ////////////////
    ///////////////////////////////////////////////////////////////////////////////
    aboutAct = new QAction(QIcon(":/resource/about.png"),tr("About"), this);
    aboutAct->setShortcut(tr("Ctrl+H"));
    aboutAct->setStatusTip(tr("app info"));
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(aboutApp()));
}

void MainWindow::createMenus()
{
    this->m_MyMenuBar = new MyMenuBar();
    this->setMenuBar(this->m_MyMenuBar);

    fileMenu = new MyMenu(tr("file"));
    fileMenu->addAction(exitAct);
    fileMenu->addSeparator();
    this->m_MyMenuBar->addMenu(fileMenu);

    helpMenu = new MyMenu(tr("help"));
    helpMenu->addSeparator();
    helpMenu->addAction(aboutAct);
    helpMenu->addSeparator();
    this->m_MyMenuBar->addMenu(helpMenu);
}

void MainWindow::createToolBars()
{
    fileToolBar = new MyToolBar(tr("file"));
    fileToolBar->addAction(exitAct);
    fileToolBar->addSeparator();
    fileToolBar->setIconSize(QSize(24,24));
    this->addToolBar(fileToolBar);


    aboutToolBar = new MyToolBar(tr("about"));
    aboutToolBar->addSeparator();
    aboutToolBar->addAction(aboutAct);
    aboutToolBar->addSeparator();
    aboutToolBar->setIconSize(QSize(24,24));
    this->addToolBar(aboutToolBar);
}

void MainWindow::createStatusBar()
{
    m_MyStatusBar = new MyStatusBar();
    this->setStatusBar(m_MyStatusBar);
    this->m_MyStatusBar->showMessage(tr("Ready"));
}

void MainWindow::showMsg(QString _msg)
{
    this->m_MyStatusBar->showMessage(_msg);
};

void MainWindow::aboutApp()
{
    QTextCodec *codec= QTextCodec::codecForLocale();
    if (!codec)
    {
        return;
    }
	QString _appName = STR_VERSION_PRODUCTNAME;
	QString _appVersion = STR_VERSION_VERSION;
#ifdef _DEBUG
	_appVersion += " X";
#endif
	_appVersion += " ";
	_appVersion += STR_VERSION_BUILD;
	QString  _appOrg = STR_VERSION_COMPANY;
	QString _appOrgCall = STR_VERSION_TELE;
	QString _appOrgFax = STR_VERSION_FAX;
	QString _appOrgDomain = STR_VERSION_WEB;
	QString _appOrgAddress = STR_VERSION_ADDRESS;
	QString _appOrgCode = STR_VERSION_POSTCODE;

    //delete ConfigIni;

    QString text = QString(
        tr("appName:%1\n"
            "Version:%2\n"
            "Company:%3\n"
            "Tele:%4\n"
            "Fax:%5\n"
            "Web Site:%6\n"
            "Address:%7\n"
            "PostCode:%8"))
        .arg(_appName)
        .arg(_appVersion)
        .arg(_appOrg)
        .arg(_appOrgCall)
        .arg(_appOrgFax)
        .arg(_appOrgDomain)
        .arg(_appOrgAddress)
        .arg(_appOrgCode);

    QMessageBox::about(this,tr("about"),text);
}
#ifdef _MIN_WIN_
void MainWindow::initTray()
{
    // this->setWindowFlags( Qt::CustomizeWindowHint/*Qt::FramelessWindowHint*/ | Qt::WindowMinimizeButtonHint | Qt::WindowStaysOnTopHint | Qt::Tool );
    Qt::WindowFlags flags = 0;
    flags |= Qt::WindowMinMaxButtonsHint;
    flags |= Qt::CustomizeWindowHint;
    this->setWindowFlags(flags);
    // this->setWindowFlags(windowFlags()&~Qt::WindowCloseButtonHint);
    // this->setWindowOpacity(1);
    this->setMouseTracking(true);
    // this->setAttribute(Qt::WA_TranslucentBackground);

    QIcon icon = QIcon(":/resource/applog.png");
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(icon);
    trayIcon->setToolTip(tr("Comparison"));
    QString titlec=tr("Comparison for tran");
    QString textc=tr("app manage interface");
    trayIcon->show();
    trayIcon->showMessage(titlec,textc,QSystemTrayIcon::Information,5000);

    //添加单/双击鼠标相应
    connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this,SLOT(trayiconActivated(QSystemTrayIcon::ActivationReason)));

    //创建监听行为
    minimizeAction = new QAction(tr("Min(&I)"), this);
    connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
    restoreAction = new QAction(tr("Rec(&R)"), this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
    helpAction = new QAction(tr("Help(&H)"), this);
    // helpAction->setShortcut(QKeySequence::HelpContents);
    connect(helpAction, SIGNAL(triggered()), this, SLOT(aboutApp()));
    quitAction = new QAction(tr("Quit(&Q)"), this);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    // connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));

    //创建右键弹出菜单
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(minimizeAction);
    trayIconMenu->addAction(restoreAction);
    // trayIconMenu->addAction(helpAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
    trayIcon->setContextMenu(trayIconMenu);
};

void MainWindow::trayiconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::Trigger:
        //单击托盘图标
    case QSystemTrayIcon::DoubleClick:
        //双击托盘图标
        this->showMaximized();
        this->raise();
        break;
    default:
        break;
    }
}

void MainWindow::changeEvent ( QEvent * event )
{
     //重点，窗口最小化时隐藏窗口，最小化到托盘
    if(event->type()==QEvent::WindowStateChange)
    {
        //changeEvent会在窗口最小化之前调用，如果不加QTimer，
        //我们把窗口隐藏了，但是Qt还以为窗口正要最小化，这样就会出错
        if(windowState() & Qt::WindowMinimized){
            QTimer::singleShot(0, this, SLOT(hide()));
            // QApplication::alert(trayIcon);
            //利用这个函数，我们就可以获得比如桌面、音乐、缓存等等的默认路径。
            //QString QDesktopServices::storageLocation(StandardLocation type)
            //调用系统默认程序打开链接
            //QDesktopServices::openUrl();
        }
    }
    QMainWindow::changeEvent(event);
}
#endif
// void MainWindow::mouseMoveEvent ( QMouseEvent * event )
// {
//     if(event->buttons()&Qt::LeftButton)
//     {
//         move(event->globalPos() - m_movePoint);
//     }
// }

// void MainWindow::mousePressEvent( QMouseEvent * event )
// {
//     if (event->button() == Qt::LeftButton)    //只能是鼠标左键移动和改变大小
//     {
//         m_movePoint = event->globalPos() - pos();    //窗口移动距离
//     }
//     QWidget::mousePressEvent(event);
// }

// void MainWindow::mouseReleaseEvent( QMouseEvent * event )
// {
//     QWidget::mouseReleaseEvent(event);
// }

void MainWindow::setFontFormat()
{
	QFont _font("Courier New", 9);
	//QFont _font("wenquanyi", 9);
	//_font.setBold(true);
	this->setFont(_font);
}

#ifdef _MIN_WIN_
void MainWindow::closeEvent(QCloseEvent *event)
{
	if (closeEventEnsure()){
		event->accept();
	} else {
		event->ignore();
	}
}

bool MainWindow::closeEventEnsure(){

	CloseCheck *m_CloseCheck = new CloseCheck();
	m_CloseCheck->setAttribute(Qt::WA_DeleteOnClose);

	if(m_CloseCheck->exec() == QDialog::Accepted){
		return true;
	}else
	{
		return false;
	}
}
#endif

void MainWindow::infoSvaeEventEnsure()
{
	QMessageBox msgBox;
	msgBox.setWindowTitle(tr("SaveEnsure"));
	msgBox.setText(tr("The application will be closed."));
	msgBox.setInformativeText(tr("Do you want to save the data info?"));
	msgBox.setStandardButtons(QMessageBox::Save | /*QMessageBox::Discard |*/ QMessageBox::Cancel);
	msgBox.setDefaultButton(QMessageBox::Save);
	int ret = msgBox.exec();

	switch (ret) {
	case QMessageBox::Save:
		// Save was clicked
		// emit this->saveNotify();
		break;
		//case QMessageBox::Discard:
		//	// Don't Save was clicked
		//	break;
	case QMessageBox::Cancel:
		// Cancel was clicked
		break;
	default:
		// should never be reached
		break;
	}
};
